import json
import re

from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
# Create your views here.


# 4. 视图
from django.views import View
from QQLoginTool.QQtool import OAuthQQ



# views.py
from oauth.models import OAuthQQUser
from users.models import User
from utils.secrect_my import MySerect


class OauthCallbackView(View):
    def get(self, request):
        #  这里面 别打断点
        code = request.GET.get('code')
        if not code:
            return JsonResponse({'code': 400, 'errmsg': "code失效了"})

        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=None
        )

        # code --token
        token = oauth.get_access_token(code)

        # token--openid
        openid = oauth.get_open_id(token)

        try:
           qquser = OAuthQQUser.objects.get(openid=openid)

           # 保持登录状态
           user = qquser.user

           login(request,user)

           # 绑定过 ----跳转到 首页
           return JsonResponse({'code': 0, 'errmsg': openid})
        except Exception as e:

            # 没绑定过-----绑定页面：
            # 加密 openid
            secrect_openid = MySerect(settings.SECRET_KEY).dumps({'openid': openid})

            return JsonResponse({'code': 400, 'access_token': secrect_openid})

    #  绑定用户
    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body)
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        openid = json_dict.get('access_token')
        sms_code = json_dict.get('sms_code')

        decode_openid = MySerect(settings.SECRET_KEY).loads(openid)
        openid = decode_openid.get('openid')


        # 判断当前的用户 是不是 新用户
        try:
            user = User.objects.get(mobile=mobile)
            # 校验密码是否正确
            if not(user and user.check_password(password)):
                return JsonResponse({'code':400, 'errmsg':'密码或用户名不正确！'})

        except Exception as e:
            # 3.核心共-增加-create--create_user
            user = User.objects.create_user(username=mobile, password=password, mobile=mobile)

        # 绑定openid
        OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )

        # 保持登录状态
        login(request, user)

        return JsonResponse({'code':0, 'errmsg':'绑定成功！'})

class QQLoginUrlView(View):
    def get(self, request):

        # 实例化对象
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=None
        )
        #  获取 QQ 登录网址
        login_url = oauth.get_qq_url()

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': login_url})